package com.sy.util;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
public class OSSUtil {

    OSSClient oss;

    OSSUtil() {
        oss = new OSSClient(Const.OSSConfig.ENDPOINT, Const.AlipayConfig.ACCESSKEYID, Const.AlipayConfig.ACCESSKEYSECRET);
    }

	/**
	 * 上传单个文件
	 * @param file
	 * @param savePath
	 * @return
	 */
	public static String putObject(MultipartFile file, String savePath) {
		String imgpath = null;
		if (file == null || file.isEmpty())
			return imgpath;
		try {
			OSSClient ossClient = new OSSClient(Const.OSSConfig.ENDPOINT, Const.AlipayConfig.ACCESSKEYID, Const.AlipayConfig.ACCESSKEYSECRET);
			InputStream objStream = file.getInputStream();

			InputStream in = file.getInputStream();
			BufferedImage buff = ImageIO.read(in);
			ObjectMetadata objMetadata = new ObjectMetadata();
			String filepath = "";
			if (buff == null)
				filepath = System.currentTimeMillis() + "";
			else
				filepath = System.currentTimeMillis() + "_" + buff.getWidth() + "*" + buff.getHeight();
			filepath += "." + (file.getOriginalFilename().split("\\."))[1].toLowerCase();
			String objKey = savePath + filepath;
			ossClient.putObject(Const.OSSConfig.BUCKET, objKey, objStream, objMetadata);
			objStream.close();
			ossClient.shutdown();
			imgpath = Const.OSSConfig.IMGPATH + objKey;
		} catch (Exception e) {
			log.info("上传文件异常", e);
		}
		return imgpath;
	}

	/**
	 * 上传多个文件
	 * @param files
	 * @param savePath
	 * @return
	 */
	public static String[] putObject(MultipartFile[] files, String savePath) {
		if (files == null)
			return new String[]{null};
		String[] imgpath = new String[files.length];
		int i = 0;
		for (MultipartFile file : files) {
			if (file == null || file.isEmpty()) {
				imgpath[i] = null;
				i++;
				continue;
			} else {
				try {
					OSSClient ossClient = new OSSClient(Const.OSSConfig.ENDPOINT, Const.AlipayConfig.ACCESSKEYID, Const.AlipayConfig.ACCESSKEYSECRET);
					InputStream objStream = file.getInputStream();
					InputStream in = file.getInputStream();
					BufferedImage buff = ImageIO.read(in);
					ObjectMetadata objMetadata = new ObjectMetadata();
					String filepath = "";
					if (buff == null)
						filepath = System.currentTimeMillis() + "";
					else
						filepath = System.currentTimeMillis() + "_" + buff.getWidth() + "*" + buff.getHeight();
					if (!StringUtils.isEmpty(file.getOriginalFilename())) {
						if (file.getOriginalFilename().contains(".")) {
							filepath += "." + (file.getOriginalFilename().split("\\."))[1].toLowerCase();
						} else {
							String contentType = file.getContentType();
							if (!StringUtils.isEmpty(contentType)) {
								String suffix = contentType.substring(contentType.lastIndexOf("/") + 1);
								filepath += "." + suffix;
							}
						}
					}
					String objKey = savePath + filepath;
					in.close();
					ossClient.putObject(Const.OSSConfig.BUCKET, objKey, objStream, objMetadata);
					objStream.close();
					ossClient.shutdown();
					imgpath[i] = Const.OSSConfig.IMGPATH + objKey;
					i++;
				} catch (Exception e) {
					log.info("上传文件异常", e);
				}
			}
		}
		return imgpath;
	}

	/**
	 * 流方式上传
	 * @param is
	 * @param savePath
	 * @param fileName
	 * @return
	 * @throws IOException
	 */
	public static String putObject(InputStream is, String savePath, String fileName) throws IOException {
        OSSClient ossClient = new OSSClient(Const.OSSConfig.ENDPOINT, Const.AlipayConfig.ACCESSKEYID, Const.AlipayConfig.ACCESSKEYSECRET);
		if (is != null) { // 判断文件是否已存在
		    if (!ossClient.doesObjectExist(Const.OSSConfig.BUCKET, savePath + fileName)) {
                ObjectMetadata objMetadata = new ObjectMetadata();
                if (fileName == null && fileName.length() == 0)
                    fileName = System.currentTimeMillis() + "";
                String filepath = (fileName.split("\\."))[0] + "." + (fileName.split("\\."))[1].toLowerCase();// 转成小写
                String objKey = savePath + filepath; //加上测试子目录，正式上线时将PathCommon.IMG_TEST配成空字符串
                ossClient.putObject(Const.OSSConfig.BUCKET, objKey, is, objMetadata);
                is.close();
                ossClient.shutdown();
                return savePath + filepath;
            } else {
		        log.info("文件上传失败，“" + savePath + fileName + "”文件已存在");
		        return null;
            }
		} else {
			log.info("文件未上传");
			return null;
		}
	}

	public static String putObject(ByteArrayOutputStream swapStream, String savePath) {
		String imgpath = null;
		try {
			OSSClient ossClient = new OSSClient(Const.OSSConfig.ENDPOINT, Const.AlipayConfig.ACCESSKEYID, Const.AlipayConfig.ACCESSKEYSECRET);
			byte[] content = swapStream.toByteArray();
			String objKey = savePath + System.currentTimeMillis() + ".jpg";
			ossClient.putObject(Const.OSSConfig.BUCKET, objKey, new ByteArrayInputStream(content));
			ossClient.shutdown();
			imgpath = Const.OSSConfig.IMGPATH + objKey;
		} catch (Exception e) {
			log.info("上传文件异常", e);
		}
		return imgpath;
	}

	public static String putObjectExport(String fileName, String[] title, String[] head1, String[] head2, List<String[]> strings, String savePath) {
		String imgpath = null;
		try {
			OSSClient ossClient = new OSSClient(Const.OSSConfig.ENDPOINT, Const.AlipayConfig.ACCESSKEYID, Const.AlipayConfig.ACCESSKEYSECRET);
			String objKey = savePath + System.currentTimeMillis() + "/";
			File directory = new File(objKey);
			if (!directory.exists()) {
				directory.mkdirs();
			}
			File file = new File(objKey, fileName);
			if (file.createNewFile()) {
				OutputStream fos = new FileOutputStream(file);
//				ExportExcel.createExcel(fos, title, head1, head2, strings);
			}
			InputStream objStream = new FileInputStream(file);
			ObjectMetadata objMetadata = new ObjectMetadata();
			ossClient.putObject(Const.OSSConfig.BUCKET, objKey + fileName, objStream, objMetadata);
			objStream.close();
			ossClient.shutdown();
			imgpath = Const.OSSConfig.IMGPATH + objKey + fileName;
			file.delete();
			directory.delete();
		} catch (Exception e) {
			log.info("上传文件异常", e);
		}
		return imgpath;
	}

    /**
     * 读取文件夹中的对象
     * @param dir
     * @return
     * @throws IOException
     */
	public OSSObject[] readDir(String dir) {
        OSSClient ossClient = oss;
		ObjectListing objectListing = ossClient.listObjects(Const.OSSConfig.BUCKET, dir);
		List<OSSObjectSummary> sums = objectListing.getObjectSummaries().stream().filter((OSSObjectSummary o) -> !dir.equals(o.getKey())).collect(Collectors.toList());
		OSSObject[] ossObjects = new OSSObject[sums.size()];
		for (OSSObjectSummary s : sums) {
            ossObjects[sums.indexOf(s)] = ossClient.getObject(new GetObjectRequest(Const.OSSConfig.BUCKET, s.getKey()));
		}
		return ossObjects;
	}

	public void shutdown(){
	    oss.shutdown();
    }
}
